/**
 * Copyright (c) 2006 George Malamidis, nutrun.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * $Author$
 * $Rev$
 */

package aerie.response;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Decorator {
    private String template;

    public Decorator(String template) {
        this.template = template;
    }

    public String decorate(String page) {
        String decoratedPage = template;
        final Map contents = getTagContentsFrom(page);
        final List tagsIn = findTagsIn(template);

        //noinspection ForLoopReplaceableByForEach
        for (Iterator iter = tagsIn.iterator(); iter.hasNext();) {
            String tag = (String) iter.next();
            final Pattern pattern = Pattern.compile("\\[decorator:\\s*" + tag + "\\s*]");
            final String tagValue = (String) contents.get(tag);
            decoratedPage = pattern.matcher(decoratedPage).replaceFirst(tagValue);
        }
        return decoratedPage;
    }

    public Map getTagContentsFrom(String page) {
        Map contents = new HashMap();

        //noinspection ForLoopReplaceableByForEach
        for (Iterator iter = findTagsIn(template).iterator(); iter.hasNext();) {
            String tag = (String) iter.next();
            if (page.indexOf(tag) == -1) continue;
            int start = page.indexOf("<" + tag +">") + tag.length() + 2;
            int end = page.indexOf("</" + tag + ">") - 1;

            StringBuffer value = new StringBuffer();
            final char[] chars = page.toCharArray();

            for (int i = start; i <= end; i++) {
                value.append(chars[i]);
            }
            //noinspection unchecked
            contents.put(tag, value.toString().trim());
        }
        return contents;
    }

    public List findTagsIn(String template) {
        List tags = new ArrayList();
        Pattern pattern = Pattern.compile("(\\[decorator:.*])");

        Matcher matcher = pattern.matcher(template);
        while (matcher.find()) {
            //noinspection unchecked
            tags.add(detokenize(matcher.group()));
        }
        return tags;
    }

    private String detokenize(String token) {
        final int start = "[decorator:".length();
        final int end = token.length() - 2;

        StringBuffer result = new StringBuffer();

        final char[] chars = token.toCharArray();

        for (int i = start; i <= end; i++) {
            result.append(chars[i]);
        }

        return result.toString().trim();
    }
}
